package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ReservationVo;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class ReservationServiceImpl implements ReservationService {

    @Autowired
    ReservationMapper reservationMapper;

    @Override
    public Integer getCancelledReservationCount(Long userId) {
        LocalDateTime begin = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);//今天开始时间
        LocalDateTime end = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);//今天结束时间
        //查询指定时间段内,当前用户的取消次数
        return reservationMapper.countCancelledReservationsWithinTimeRange(begin, end, userId);
    }

    @Override
    public void save(ReservationDto dto) {
        Reservation bean = BeanUtil.toBean(dto, Reservation.class);
        bean.setStatus(0);
        reservationMapper.insert(bean);
    }

    @Override
    public List<ReservationVo> countByTime(Long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = sdf.format(new Date(time));

        // 计算开始时间和结束时间
        String startTime = dateTime.substring(0, 11) + " 00:00:00";
        String endTime = dateTime.substring(0, 11) + " 23:59:59";

        return reservationMapper.countByTime(startTime, endTime);
    }

    @Override
    public PageResponse pageList(Integer pageSize, Integer pageNum , Integer status) {
        Long mgtUserId = UserThreadLocal.getUserId();
        PageHelper.startPage(pageNum, pageSize);
        Page<ReservationVo> list = reservationMapper.pageList(mgtUserId,status);
        PageResponse pageResponse = PageResponse.of(list,ReservationVo.class);
        return pageResponse;
    }

    @Override
    public void cancel(Long id) {
        reservationMapper.cancel(id);
    }
}
